<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">

      <Merchandiser v-if="$store.getters.usertype===0" ref="merchandiserDom" @callback="callbackHandler" />

      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="isgrounding">
        <el-select
          v-model="queryParams.isgrounding"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dicts.isgrounding"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="排序" prop="sortOrder" />

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="btnSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh-left" size="mini" @click="btnReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!--功能区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-requiredMerchant
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-requiredMerchant
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-requiredMerchant
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
        >批量下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区table-->
    <el-table v-loading="loading" :data="tableData.rows" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" prop="id" width="100" />
      <el-table-column label="商家名称" prop="merchantName" :show-overflow-tooltip="true" />
      <el-table-column label="分类名称" prop="categoryName" :show-overflow-tooltip="true" />
      <el-table-column label="商品名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="商品价格" prop="price" :show-overflow-tooltip="true" />
      <el-table-column label="商品图片">
        <template slot-scope="scope">
          <img v-if="scope.row.picture" :src="scope.row.picture" width="150">
          <el-tag v-else type="danger">暂无图片</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isgrounding===1">上架</el-tag>
          <el-tag v-else type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column v-if="$store.getters.usertype===1" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>

          <el-button
            v-if="scope.row.isgrounding===0"
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="handleUpOrDown(scope.row,1)"
          >
            上架
          </el-button>

          <el-button
            v-if="scope.row.isgrounding===1"
            size="mini"
            type="text"
            icon="el-icon-bottom"
            @click="handleUpOrDown(scope.row,0)"
          >
            下架
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!--分页条 -->
    <div style="margin-top: 10px;">
      <el-pagination
        v-if="tableData.total>0"
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 30, 40,50,100]"
        :page-size="queryParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增和修改对话框-->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜品分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="菜品价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入菜品价格" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.isgrounding">
                <el-radio
                  v-for="dict in dicts.isgrounding"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="口味配置">
              <div class="flavorBox">                <!--商品本身有口味-->
                <div v-if="form.dishFlavors && form.dishFlavors.length != 0" class="flavor">
                  <div class="title">
                    <span>口味名（3个字内）</span>
                    <span class="kwbq">口味标签（输入标签回车添加）</span>
                  </div>
                  <div v-for="(item ,index ) in form.dishFlavors" :key="index" class="cont">
                    <!--口味名称 -->
                    <el-autocomplete
                      v-model="item.name"
                      class="inline-input"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入内容"
                      :maxlength="3"
                      show-word-limit
                      @select="handleSelect"
                    >
                      <template slot-scope="{ item }">
                        <span>{{ item }}</span>
                      </template>
                    </el-autocomplete>

                    <!-- 口味明细 -->
                    <div class="labItems">
                      <el-tag v-for="(tag,ind) in item.value" :key="tag" closable :disable-transitions="false" @close="handleClose(item,ind)">
                        {{ tag }}
                      </el-tag>
                      <el-input
                        v-if="item.inputVisible"
                        ref="saveTagInput"
                        v-model="item.inputValue"
                        class="input-new-tag"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(item)"
                        @blur="handleInputConfirm(item)"
                      />
                      <el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ New Tag</el-button>

                    </div>

                    <span class="delFlavor delBut non" @click="delFlavor(index)">删除</span>

                  </div>                </div>
                <el-button type="warning" @click="addFlavor()">添加口味</el-button>
              </div>

            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="菜品图片" prop="picture">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="headers"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.picture" :src="form.picture" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <div style="display:none;">
                <el-input v-model="form.picture" style="width:0;height:0;" />
              </div>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="菜品描述">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import DictDataMixin from '@/mixin/DictDataMixin.js'
import PageMixin from '@/mixin/PageMixin.js'
import AddOrEditMixin from '@/mixin/AddOrEditMixin.js'
import { dataApi, addApi, editApi, findByIdApi, deleteByIdApi } from '@/api/product.js'
import { merchandiseCategoryApi } from '@/api/category.js'
import { flavorListApi } from '@/api/dictdata.js'
import Merchandiser from '@/components/Merchandiser/index.vue'
export default {
  components: {
    Merchandiser
  },
  mixins: [DictDataMixin, PageMixin, AddOrEditMixin],
  // 查询通字典的2个对象的值
  dictkeys: ['isgrounding'],
  data() {
    return {
      fetchDataApi: dataApi,
      editApi: editApi,
      addApi: addApi,
      findByIdApi: findByIdApi,
      deleteByIdApi: deleteByIdApi,
      primaryKey: 'id',
      // 是否显示地图选择框
      mapShow: false,
      rules: {
        name: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ]
      },
      // 口味
      flavorList: [],
      // 分类列表
      categoryList: []
    }
  },
  created() {
    this.initFormValue()
    this.initData()
  },
  methods: {
    initData() {
      flavorListApi().then(resp => {
        this.flavorList = resp.data
      })

      merchandiseCategoryApi().then(resp => {
        this.categoryList = resp.data
      })
    },
    initFormValue() {
      this.form = {
        picture: undefined,
        isgrounding: 0

      }
    },
    handleExport() {
      this.download('/api/merchandiser/excel', this.queryParams, `商家信息_${new Date().getTime()}.xlsx`)
    },
    // 图片上传成功以后返回的数据(json, file[blob]数据)
    handleAvatarSuccess(res, file) {
      this.form.picture = res.data.url
    },
    // 选择商家的回调函数
    callbackHandler(row) {
      this.queryParams.merchantId = row.id
    },
    // 查询重置
    btnReset() {
      this.queryParams = {
        page: 1,
        size: 10
      }
      this.btnSearch()
      if (this.$refs.merchandiserDom) {
        // 父组件要调用子组件中的方法  clearQueryForm
        this.$refs.merchandiserDom.clearQueryForm()
      }
    },
    // 添加口味
    addFlavor() {
      console.log('add')
      if (!this.form.dishFlavors) {
        // 动态分配数据 向响应式对象中添加一个 property，并确保这个新 property 同样是响应式的，且触发视图更新 Vue.set()语法
        // this.form.dishFlavors = []    值变化了，但是页面没有变化
        this.$set(this.form, 'dishFlavors', [])
      }

      if (this.form.dishFlavors.filter(p => p.name === '').length === 0) {
        this.form.dishFlavors.push({ name: '', value: [], inputVisible: false, inputValue: '' })
      }
    },
    handleClose(item, index) {
      item.value.splice(index, 1)
    },
    showInput(item) {
      item.inputVisible = true
    },
    handleInputConfirm(item) {
      if (item.value.length >= 6) {
        this.$message.error('口味标签不能超过6个')
      } else {
        const inputValue = item.inputValue
        if (inputValue) {
          item.value.push(inputValue)
        }
      }

      item.inputVisible = false
      item.inputValue = ''
    },

    // 根据下标删除form的口味
    delFlavor(index) {
      this.form.dishFlavors.splice(index, 1)
    },
    // 自动建议选中
    handleSelect(item) {
      // 判断是否在口味集合中
      if (item) {
        var result = this.flavorList.filter(p => p.name === item)
        // 得到表单中最后一个口味对象
        var findObj = this.form.dishFlavors.filter(p => p.name === undefined || p.name === item)
        if (findObj.length > 1) {
          this.$message.error('已经存在相同的口味名!')
        } else {
          var obj = findObj[0]
          obj.name = item
          // 在里面
          if (result.length > 0) {
            obj.value = result[0].value
          }
        }
      }
    },
    querySearch(queryString, cb) {
      var arr = this.flavorList
      // 调用 callback 返回建议列表的数据
      var results = queryString ? arr.filter(p => p.name.startsWith(queryString)) : arr
      var mapValue = results.map(p => p.name)
      console.log(mapValue)
      cb(mapValue)
    }
  }
}
</script>
</script>

<style scoped>
  .el-tag + .el-tag {
          margin-left: 10px;
        }
        .button-new-tag {
          margin-left: 10px;
          height: 32px;
          line-height: 30px;
          padding-top: 0;
          padding-bottom: 0;
        }
        .input-new-tag {
          width: 90px;
          margin-left: 10px;
          vertical-align: bottom;
        }

     .flavorBox .flavor {
       border: solid 1px #dfe2e8;
       border-radius: 3px;
       padding: 15px;
       background: #fafafb;
     }
     .flavorBox .flavor .title {
       color: #606168;
     }

     .flavor .el-autocomplete {
        width: 150px;
     }

     .flavorBox .flavor .cont .labItems {
       display: inline-block;
       border-radius: 3px;
       min-height: 39px;
       border: solid 1px #d8dde3;
       background: #fff;
       padding: 0 5px;
       margin-left: 10px;
     }

     .flavorBox .flavor .cont  .delFlavor {
       display: inline-block;
       padding: 0 10px;
       color: #f19c59;
       cursor: pointer;
     }

     .flavorBox .flavor .cont {
       margin: 10px 0;
     }
     .flavorBox .title   .kwbq{
        margin-left: 45px;
     }
</style>
